<template>
  <el-dialog
    class="gl_dialog_TitleLine"
    width="1080px"
    :title="title"
    :append-to-body="true"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div v-loading="loading" class="edit_event_teamplate">
      <el-row :gutter="20" class="gl_mb_15">
        <el-col :span="9">
          <el-radio v-model="chooseRadio" label="sys">系统项目模板</el-radio>
          <el-select v-model="sysEventTemplateId" placeholder="请选择模板" size="mini" @change="getSysTemplateInfo()">
            <el-option v-for="item in sysEventTemplateList" :key="item.value" :value="item.value" :label="item.name" />
          </el-select>
        </el-col>
        <el-col :span="15">
          <el-radio v-model="chooseRadio" label="categoryHistory">已建立项目</el-radio>
          <el-select v-model="chooseGameId" placeholder="请选择赛事" size="mini" :popper-append-to-body="false" @change="getCategoryHistoryList">
            <el-option v-for="item in gameList" :key="item.id" :value="item.id" :label="item.name">
              <div style="max-width: 480px;" class="gl_ellipsis" :title="item.name">{{ item.name }}</div>
            </el-option>
          </el-select>
          <el-select v-model="categoryHistoryQO.id" class="gl_ml_10" placeholder="请选择项目" size="mini" @change="getCategoryHistoryInfo()">
            <el-option v-for="item in categoryHistoryList" :key="item.id" :value="item.id" :label="item.name">
              <div style="max-width: 350px;" class="gl_ellipsis" :title="item.name">{{ item.name }}</div>
            </el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-table
        class="gl_my_5"
        :data="tableData"
        stripe
        size="mini"
        style="width: 100%"
      >
        <el-table-column type="expand" :width="40" style="padding: 5px;">
          <template v-if="row.eventGroups" slot-scope="{ row }">
            <el-table :data="row.eventGroups" :show-header="false" size="mini" style="width: 100%">
              <el-table-column label="组别名称" align="center" :width="280">
                <template slot-scope="scope">
                  <div>{{ scope.row.name }}</div>
                  <div>({{ scope.row.startBirthDate && scope.row.startBirthDate.substring(0, 10) }} - {{ scope.row.endBirthDate && scope.row.endBirthDate.substring(0, 10) }})</div>
                </template>
              </el-table-column>
              <el-table-column prop="levelName" label="具体级别" :mn-width="280">
                <template slot-scope="scope">
                  <template v-if="scope.row.events.length && (scope.row.events[0].genderCode === 'M' || scope.row.events[0].genderCode === 'W')">
                    <div>
                      男子组：
                      <template v-for="(eventItem, eventIndex) in scope.row.events">
                        <span v-if="eventItem.genderCode === 'M'" :key="eventIndex" class="event_item">{{ eventItem.name }}
                          <template v-if="eventItem.weightClasses && eventItem.weightClasses.length > 0">
                            {{ eventItem.weightClasses.length > 0 ? '(' : '' }}
                            <span v-for="(jtem, jndex) in eventItem.weightClasses" :key="jndex">
                              {{ jtem.name }}{{ jndex == eventItem.weightClasses.length-1 ? '' : ',' }}
                            </span>
                            {{ eventItem.weightClasses.length > 0 ? ')' : '' }}
                          </template>
                        </span>
                      </template>
                    </div>
                    <div>女子组：
                      <template v-for="(eventItem, eventIndex) in scope.row.events">
                        <span v-if="eventItem.genderCode === 'W'" :key="eventIndex" class="event_item">{{ eventItem.name }}
                          <template v-if="eventItem.weightClasses && eventItem.weightClasses.length > 0">
                            {{ eventItem.weightClasses.length > 0 ? '(' : '' }}
                            <span v-for="(jtem, jndex) in eventItem.weightClasses" :key="jndex">
                              {{ jtem.name }}{{ jndex == eventItem.weightClasses.length-1 ? '' : ',' }}
                            </span>
                            {{ eventItem.weightClasses.length > 0 ? ')' : '' }}
                          </template>
                        </span>
                      </template>
                    </div>
                  </template>
                  <template v-else>
                    <div>
                      具体级别：
                      <template v-for="(eventItem, eventIndex) in scope.row.events">
                        <span :key="eventIndex" class="event_item">{{ eventItem.name }}
                          <template v-if="eventItem.weightClasses && eventItem.weightClasses.length > 0">
                            {{ eventItem.weightClasses.length > 0 ? '(' : '' }}
                            <span v-for="(jtem, jndex) in eventItem.weightClasses" :key="jndex">
                              {{ jtem.name }}{{ jndex == eventItem.weightClasses.length-1 ? '' : ',' }}
                            </span>
                            {{ eventItem.weightClasses.length > 0 ? ')' : '' }}
                          </template>
                        </span>
                      </template>
                    </div>
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="项目名称" :min-width="280" />
        <el-table-column prop="systemName" label="项目制度" :width="120">
          <template slot-scope="{ row }">
            {{ row.eventType && row.eventType.name }}
          </template>
        </el-table-column>
        <el-table-column prop="typeName" label="项目类型" :width="120">
          <template slot-scope="{ row }">
            {{ row.registerType && row.registerType.name }}
          </template>
        </el-table-column>
      </el-table>
      <el-row class="gl_mt_15">
        <el-col :span="24" align="right">
          <el-button type="default" size="mini" @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" size="mini" @click="handleChooseTeamplate">确定</el-button>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>
<script>
import {
  api_GET_EventsManagementCategoryTemplateBriefTemlatesInfo,
  api_GET_EventsManagementCategoryTemplateId,
  api_GET_EventsManagementCategoryId,
  api_GET_EventsManagementCategory,
  api_GET_EventsManagementCompetitionEditableList
} from '@/extend/api/gameswaggerApi/app';
export default {
  name: 'ChooseEventTemplate',
  data() {
    return {
      loading: false,
      title: '项目模板',
      chooseRadio: 'sys',
      dialogVisible: false,
      tableData: [],
      // 系统项目模板
      sysEventTemplateList: [],
      sysEventTemplateId: '',
      // 已建立项目模板
      categoryHistoryList: [],
      categoryHistoryQO: {
        id: '',
        IncludeEventGroup: true,
        IncludeEvent: true,
        IncludeRegisterType: true,
        IncludeEventType: true
      },
      gameList: [],
      chooseGameId: '',
      isLeague: false
    };
  },
  watch: {
    chooseRadio() {
      if (this.chooseRadio === 'sys') {
        this.getSysTemplateInfo();
      }
      if (this.chooseRadio === 'categoryHistory') {
        this.getCategoryHistoryInfo();
      }
    }
  },
  created() {
    this.isLeague = this.$route.params.parentId || '';
  },
  methods: {
    init() {
      this.chooseRadio = 'sys';
      this.sysEventTemplateId = '';
      this.categoryHistoryList = [];
      this.sysEventTemplateList = [];
      this.gameList = [];
      this.chooseGameId = '';
      this.categoryHistoryQO = {
        id: '',
        IncludeEventGroup: true,
        IncludeEvent: true,
        IncludeRegisterType: true,
        IncludeCategoryRound: true,
        IncludeWeightClasses: true,
        IncludeEventType: true
      };
    },
    open() {
      this.init();
      this.getSysTemplateList().then(() => {
        this.getSysTemplateInfo();
      });
      this.getGameList().then(res => {
        if (this.gameList.length) {
          this.chooseGameId = this.gameList[0].id;
          this.getCategoryHistoryList(this.chooseGameId);
        }
      });
      this.dialogVisible = true;
    },
    // 选择模板
    handleChooseTeamplate() {
      if (!this.tableData.length) {
        this.$message({ type: 'warning', message: '请选择模板！' });
        return;
      }
      this.dialogVisible = false;
      console.log(this.tableData);
      this.$emit('openAddEvent', this.tableData[0]);
    },
    // 获取系统项目模板
    getSysTemplateList() {
      return new Promise((resolve, reject) => {
        api_GET_EventsManagementCategoryTemplateBriefTemlatesInfo().then(res => {
          this.sysEventTemplateList = res || [];
          this.sysEventTemplateId = this.sysEventTemplateList.length && this.sysEventTemplateList[0].value || '';
          resolve(res);
        }, error => {
          this.$message({ type: 'error', message: '获取系统项目模板失败！' });
          reject(error);
        });
      });
    },
    // 根据系统模板获取系统模板详情
    getSysTemplateInfo() {
      return new Promise((resolve, reject) => {
        if (!this.sysEventTemplateId || this.chooseRadio !== 'sys') return;
        this.loading = true;
        api_GET_EventsManagementCategoryTemplateId(this.sysEventTemplateId).then(res => {
          this.loading = false;
          this.tableData = res && [res] || [];
          for (let i = 0; i < this.tableData.length; i++) {
            const item = this.tableData[i];
            for (let j = 0; j < item.eventGroups.length; j++) {
              const jtem = item.eventGroups[j];
              jtem.events = jtem.events.sort((a, b) => a.sortOrder - b.sortOrder);
            }
          }
          resolve(res);
        }, error => {
          this.loading = false;
          this.$message({ type: 'error', message: '获取系统项目模板详情失败！' });
          reject(error);
        });
      });
    },
    // 获取赛事列表
    getGameList() {
      // const form = {
      //   TypeCode: this.isLeague ? 'League' : 'Independent'
      // };
      return new Promise((resolve, reject) => {
        api_GET_EventsManagementCompetitionEditableList({ TypeCode: 'Independent', IsFinal: false, HasParent: false }).then(res => {
          this.gameList = res.items.filter(item => item.id !== this.$route.params.id);
          resolve(res);
        });
      }, error => {
        reject(error);
        this.$message({ type: 'error', message: error.error && error.error.message || '' });
      });
    },
    // 获取已建立项目列表
    getCategoryHistoryList(id) {
      return new Promise((resolve, reject) => {
        const categoryQO = {
          IncludeEventGroup: true,
          IncludeEvent: true,
          IncludeGender: true,
          IncludeEventType: true,
          IncludeRegisterType: true,
          IncludeWeightClasses: true,
          CompetitionId: id,
          Sorting: 'creationTime'
        };
        api_GET_EventsManagementCategory(categoryQO).then(res => {
          this.categoryHistoryList = res.items || [];
          this.categoryHistoryQO.id = this.categoryHistoryList.length && this.categoryHistoryList[0].id || '';
          if (this.chooseRadio === 'categoryHistory') {
            this.tableData = [];
          }
          this.getCategoryHistoryInfo();
          resolve(res);
        }, error => {
          this.$message({ type: 'error', message: '获取系统项目模板失败！' });
          reject(error);
        });
      });
    },
    // 根据已建立项目Id获取模板详情
    getCategoryHistoryInfo() {
      return new Promise((resolve, reject) => {
        if (!this.categoryHistoryQO.id || this.chooseRadio !== 'categoryHistory') return;
        this.loading = true;
        api_GET_EventsManagementCategoryId(this.categoryHistoryQO.id, this.categoryHistoryQO).then(res => {
          this.loading = false;
          this.tableData = res && [res] || [];
          for (let i = 0; i < this.tableData.length; i++) {
            const item = this.tableData[i];
            for (let j = 0; j < item.eventGroups.length; j++) {
              const jtem = item.eventGroups[j];
              jtem.events = jtem.events.sort((a, b) => a.sortOrder - b.sortOrder);
            }
          }
          resolve(res);
        }, error => {
          this.loading = false;
          this.$message({ type: 'error', message: '获取系统项目模板详情失败！' });
          reject(error);
        });
      });
    }
  }
};
</script>
<style>
.edit_event_teamplate .el-table__expanded-cell {
  padding: 5px;
}
.event_item {
  padding: 2px 5px;
  color: #117CDF;
  background: rgba(243, 249, 255, 1);
  margin-right: 10px;
}
</style>
